package com.example.zhinongbao.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zhinongbao.R;
import com.example.zhinongbao.model.Message;

import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {

    private final List<Message> messageList;

    public MessageAdapter(List<Message> messageList) {
        this.messageList = messageList;
    }

    public void setMessages(List<Message> messages) {
        this.messageList.clear();
        this.messageList.addAll(messages);
        notifyDataSetChanged();
    }

    public void addMessage(Message message) {
        this.messageList.add(message);
        notifyItemInserted(messageList.size() - 1);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_message, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Message message = messageList.get(position);

        if (message.isSent()) {
            // 显示发送的消息布局
            holder.layoutSent.setVisibility(View.VISIBLE);
            holder.layoutReceived.setVisibility(View.GONE);
            holder.tvSentContent.setText(message.getContent());
            holder.tvSentTime.setText(message.getFormattedTime());
        } else {
            // 显示接收的消息布局
            holder.layoutReceived.setVisibility(View.VISIBLE);
            holder.layoutSent.setVisibility(View.GONE);
            holder.tvReceivedContent.setText(message.getContent());
            holder.tvReceivedTime.setText(message.getFormattedTime());
        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout layoutReceived;
        LinearLayout layoutSent;
        TextView tvReceivedContent;
        TextView tvReceivedTime;
        TextView tvSentContent;
        TextView tvSentTime;

        public ViewHolder(View itemView) {
            super(itemView);
            layoutReceived = itemView.findViewById(R.id.layout_received);
            layoutSent = itemView.findViewById(R.id.layout_sent);
            tvReceivedContent = itemView.findViewById(R.id.tvReceivedContent);
            tvReceivedTime = itemView.findViewById(R.id.tvReceivedTime);
            tvSentContent = itemView.findViewById(R.id.tvSentContent);
            tvSentTime = itemView.findViewById(R.id.tvSentTime);
        }
    }
}